package kaoshi.servlet_2;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import com.alibaba.fastjson.JSON;
import kaoshi.entity.person;
import kaoshi.service.impl.personServiceImpl;

@WebServlet("/add.do")
public class InsertServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out =response.getWriter();
        //拿到前台传递的Json字符串
        String jsonName=request.getParameter("obj");
        //把Json字符串转换成Admin对象 并把json格式中的值放入Admin属性中
        person person= JSON.parseObject(jsonName,person.class);
        //拿到属性值 测试是否转换成功
        System.out.println(person.getId()+"\t"+person.getName()+"\t"+person.getSex()+"\t"+
                person.getAge()+"\t"+person.getRank()+"\t"+person.getBumeng());
        String name=person.getName();
        String sex=person.getSex();
        int age=person.getAge();
        String rank=person.getRank();
        String bumeng=person.getBumeng();
        personServiceImpl impl=new personServiceImpl();
        person person1=new person(name,sex,age,rank,bumeng);
        int count=impl.insert(person1);
        if (count>0){
            //找到数据库中最新的那条数据 转换成json格式传回到html中
            person MaxID_admin=impl.inquireMaxId();
            out.print(MaxID_admin.toString());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
